package com.breaking.second.utils;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.Editable;

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class StringUtil {
    /**
     * 获取应用的版本名称
     *
     * @param context 应用上下文
     * @return 应用的版本名称
     */
    public static String getAppVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "Unknown";
        }
    }

    /**
     * 获取应用的版本号
     *
     * @param context 应用上下文
     * @return 应用的版本号
     */
    public static int getAppVersionCode(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }
    public static void copyText(Context context, String name) {
        // 获取剪贴板管理器
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 要复制的文字
        String textToCopy = "这是要复制的文字";
        // 创建剪贴板数据
        ClipData clip = ClipData.newPlainText("text", textToCopy);
        // 将数据放到剪贴板上
        clipboard.setPrimaryClip(clip);
    }

    public static boolean isEmpty(Editable editable) {
        if (editable == null) {
            return true;
        }
        return editable.toString().trim().isEmpty();
    }

    public static String toTime(Instant instant) {
        ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Shanghai"));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return zdt.format(formatter);
    }

    @SuppressLint("DefaultLocale")
    public static String formatNumber(double number) {
        if (number >= 1_000_000_000) {
            return String.format("%.2fB", number / 1_000_000_000);
        } else if (number >= 1_000_000) {
            return String.format("%.2fM", number / 1_000_000);
        } else if (number >= 10_000) {
            return String.format("%.2fW", number / 10_000);
        } else if (number >= 1_000) {
            return String.format("%.0fK", number / 1_000);
        } else {
            return String.format("%.0f", number);
        }
    }
}
